﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using Chowpoo.Sql;
using CourseSystem.Core.Entities;
using CourseSystem.Core.SqlServerDAL;

namespace CourseSystem.Core.BLL
{
    public class PostsAttachBLL : CommonBLL<PostsAttachInfo, PostsAttachDAL>
    {
        public static PostsAttachInfo Get(int id)
        {
            using (var dal = new PostsAttachDAL())
            {
                var re = dal.SelectSingle(o => o.Id == id);
                return re;
            }
        }

        public static bool Del(int id)
        {
            using (var dal = new PostsAttachDAL())
            {
                return dal.Delete(o => o.Id == id) != null;
            }
        }

        public static List<PostsAttachInfo> GetByExpress(Expression<Func<PostsAttachInfo, bool>> expression)
        {
            using (var dal = new PostsAttachDAL())
            {
                return dal.Select(expression);
            }
        }

        public static bool DelFileByExpress(Expression<Func<PostsAttachInfo, bool>> expression)
        {
            using (var dal = new PostsAttachDAL(Settings.ConnectionName))
            {
                var list = dal.Select(expression);
                return DelFileByList(list);
            }
        }

        public static bool DelFileByList(List<PostsAttachInfo> list)
        {
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.FileName))
                    File.Delete(HttpContext.Current.Server.MapPath("~/") + item.FileName);
            }
            using (var dal = new PostsAttachDAL(Settings.ConnectionName))
            {
                return dal.Delete(list) != null;
            }
        }
    }
}
